import { ref } from 'vue';

/**
 * @description 封装和复用拖拽相关的交互逻辑
 * @param {object} position - 包含 x 和 y ref 的位置对象
 * @returns {object} - 包含拖拽状态和事件处理函数的对象
 */
export function useDrag(position) {
  const dragging = ref(false);

  /**
   * @description 鼠标按下事件处理函数
   * @param {MouseEvent} event - 鼠标事件
   */
  function onMouseDown(event) {
    dragging.value = true;
    const startMouseX = event.clientX;
    const startMouseY = event.clientY;
    const startElementX = position.x.value;
    const startElementY = position.y.value;

    /**
     * @description 鼠标移动事件处理函数
     * @param {MouseEvent} event - 鼠标事件
     */
    function onMouseMove(event) {
      if (dragging.value) {
        const deltaX = event.clientX - startMouseX;
        const deltaY = event.clientY - startMouseY;
        position.x.value = startElementX + deltaX;
        position.y.value = startElementY + deltaY;
      }
    }

    /**
     * @description 鼠标释放事件处理函数
     */
    function onMouseUp() {
      dragging.value = false;
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('mouseup', onMouseUp);
    }

    document.addEventListener('mousemove', onMouseMove);
    document.addEventListener('mouseup', onMouseUp);
  }

  return { onMouseDown, isDragging: dragging };
}